//
//  RadioButton.m
//  vImageStudy
//
//  Created by Evan Xie on 8/7/15.
//  Copyright (c) 2015 Family Wings. All rights reserved.
//

#import "RadioButton.h"

@implementation RadioButton


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self _commonInit];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    [self _commonInit];
}

- (void)_commonInit
{
    _borderColor = [UIColor blueColor];
    self.backgroundColor = [UIColor clearColor];
    self.tintColor = [UIColor clearColor];
    
    [self addTarget:self action:@selector(buttonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setBorderColor:(UIColor *)borderColor
{
    if (_borderColor != borderColor) {
        _borderColor = borderColor;
        
        [self setNeedsDisplay];
    }
}

- (void)setSelected:(BOOL)selected
{
    if (self.isSelected == selected) {
        return;
    }
    
    [super setSelected:selected];
    
    [self setNeedsDisplay];
    
    if (selected && [self.delegate respondsToSelector:@selector(radioButtonDidSelect:)]) {
        [self.delegate radioButtonDidSelect:self];
    }
}

- (void)buttonDidPressed:(id)sender
{
    self.selected = YES;
}


- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    float width = CGRectGetWidth(self.bounds);
    float height = CGRectGetHeight(self.bounds);
    float squareSize = MIN(width, height);
    
    CGRect drawingRect = CGRectMake((width-squareSize)/2.0, (height-squareSize)/2.0, squareSize, squareSize);
    
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(contextRef, 1.0);
    CGContextSetStrokeColorWithColor(contextRef, _borderColor.CGColor);
    CGContextSetFillColorWithColor(contextRef, _borderColor.CGColor);
    
    CGContextStrokeEllipseInRect(contextRef, CGRectInset(drawingRect, 2, 2));
    
    if (self.isSelected) {
        CGContextFillEllipseInRect(contextRef, CGRectInset(drawingRect, squareSize*0.3, squareSize*0.3));
    }
}


@end
